package com.wang.common.aes;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @Author wang
 * @Date 2024/9/22 18:18
 * @PackageName:com.wang.common.config
 * @ClassName: AESEncryptConfig
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class AESEncryptService {

    private static final Logger log = LoggerFactory.getLogger(AESEncryptService.class);

    private final EncryptProperties encryptProperties;

    public AESEncryptService(EncryptProperties encryptProperties) {
        this.encryptProperties = encryptProperties;
    }

    // 加密方法
    public String encrypt(String content) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(encryptProperties.getKey().getBytes(StandardCharsets.UTF_8), Constants.AES);
            IvParameterSpec iv = new IvParameterSpec(encryptProperties.getIv().getBytes(StandardCharsets.UTF_8));

            Cipher cipher = Cipher.getInstance(Constants.AES_CBC_CIPHER);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

            byte[] encryptedData = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            log.error("加密失败：", e);
            throw new RuntimeException("加密失败", e);
        }
    }

    // 解密方法
    public String decrypt(String encryptedContent) {
        try {
            byte[] decodedContent = Base64.getDecoder().decode(encryptedContent);
            SecretKeySpec secretKey = new SecretKeySpec(encryptProperties.getKey().getBytes(StandardCharsets.UTF_8), Constants.AES);
            IvParameterSpec iv = new IvParameterSpec(encryptProperties.getIv().getBytes(StandardCharsets.UTF_8));

            Cipher cipher = Cipher.getInstance(Constants.AES_CBC_CIPHER);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

            byte[] decryptedData = cipher.doFinal(decodedContent);
            return new String(decryptedData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("解密失败：", e);
            throw new RuntimeException("解密失败", e);
        }
    }
}
